<template>
  <div class="bx--grid bx--grid--full-width bx--grid--no-gutter test-page">
    <div class="bx--row">
      <div class="bx--col-lg-16">    
            <h1>TestPage1 -  {{paramData.id}}</h1>
      </div>
    </div>
    <cv-form>
      <div class="bx--row">
        <div class="bx--col-lg-4">
          <cv-text-input label="Organization" placeholder="Organization name"  v-model.trim="testForm.orgName"></cv-text-input>         
        </div>
        <div class="bx--col-lg-4">
          <cv-select label="Select server" v-model="testForm.selectedServer">
              <template v-for='(item, index) in serverList'>
                <cv-select-option :value="item.url" :key="index">{{item.name}}</cv-select-option>
              </template>
            </cv-select>           
        </div>
        <div class="bx--col-lg-8" style="display: flex; justify-content: flex-start;align-items:flex-end;">
          <cv-button type="button" kind="primary" :small="true" @click="doSearch()">Search</cv-button>
        </div>
      </div>
      <div class="bx--col-lg-16">
        <span style="color:red">{{errMsg}}</span>
      </div>      
      <div class="bx--row">
        <template v-for='(value, key) in apiData'>  
          <div class="bx--col-lg-8" :key="key">
            <cv-text-input :label="key"  placeholder="" v-model.trim="apiData[key]"></cv-text-input>
          </div>                        
        </template>      
      </div>
    </cv-form>
    <cv-toast-controller ref="toast" />
    <cv-loading :active="loading" :overlay="true"></cv-loading>
   <cv-modal
      ref="validateModal"
      close-aria-label="close"
      size="xs"
      :primary-button-disabled="false"
      :visible="false"
      @modal-shown="actionShown('validateModal')"
      @modal-hidden="actionHidden('validateModal')"
      @modal-hide-request="actionHideRequest('validateModal',$event)"      
      @primary-click="actionPrimary('validateModal')"
      @secondary-click="actionSecondary('validateModal')"
      :auto-hide-off="true">
      <template slot="label">{{validateMsg.label}}</template>
      <template slot="title">{{validateMsg.title}}</template>
      <template slot="content">{{validateMsg.content}}</template>
      <template slot="secondary-button">Close</template>
    </cv-modal>    
  </div>
</template>

<script>
import axios from 'axios';
import Qs from "qs";
// import { required, minLength, maxLength, sameAs } from 'vuelidate/lib/validators';
import { CvToastController } from "@/components/carbon/cv-toast-controller";

const localAPIUrl = process.env.VUE_APP_API_LOCAL_BASE_URL;
const githubAPIiUrl = process.env.VUE_APP_API_GHITHUB_BASE_URL;

export default {
  name: 'TestPage1',
  components: {  
    "cv-toast-controller": CvToastController,
  },  
  data() {
    return {
      loading:false,
      testForm: {
        orgName:"",
        selectedServer:"",
      },
      validateMsg:{label:"",title:"",content:""},
      errMsg:"",
      apiData:{},      
      serverList:[
        {name:"Github",url:`${githubAPIiUrl}/orgs`},
        {name:"Local",url:`${localAPIUrl}/apilocal.php`},
      ],
    };
  },
  // validations: {
  //   testForm: {
  //     orgName: {
  //       required
  //     },
  //   }
  // },  
  methods: {
    async doSearch(){
      this.errMsg="";
      if(this.testForm.orgName.trim()===""){
        // alert("Please input organization name.");
        this.validateMsg.content="Please input organization name.";
        this.$refs["validateModal"].show();
        return;
      }
      if(this.testForm.selectedServer===""){
        // alert("Please input organization name.");
        this.validateMsg.content="Please select server.";
        this.$refs["validateModal"].show();
        return;
      }            
      this.apiData={};
      this.loading=true;
      await this.getAPIData(this.testForm.orgName);
      this.loading=false;
    },
    async getAPIData(org){
      //https://api.github.com/orgs/ibm https://api.github.com/graphql
      let ajaxConfig={        
        headers: {"Content-Type":"application/json","Accept":"application/json" },
        method:"get",
        // url:`${githubAPIiUrl}/orgs/${org}`,
        // url:`${localAPIUrl}/apilocal.php/${org}`,
        url:`${this.testForm.selectedServer}/${org}`,
        params:{},   
        validateStatus: function (status) {
          return status <500;
        },               
      }
      console.log("ajaxConfig is:",ajaxConfig);
      let response = await this.requestAjax(ajaxConfig);
      if(response!==undefined){
        let responseData=response.data;
        if(response.status===200 && responseData.message===undefined){
          for(let key in responseData){
            if(responseData[key]!==null){
              responseData[key]=responseData[key].toString();
            }
          }
          this.apiData=responseData;
        }else{
          this.apiData={};
          let message=this.echoString(responseData.message);
          this.errMsg=`Response code:${response.status},message:${message}`;
          // this.$refs.toast.error("responseData.message");
        }        
      }else{
        this.apiData={};
        this.$refs.toast.error("getAPIData fail");
      }
      console.log("apiData",this.apiData);
    },
    async requestAjax(ajaxConfig){
      try {
        let response = await axios.request(ajaxConfig);
        return new Promise((resolve, reject) => {
            if (response) {
                console.log("resolve response");
                resolve(response)
            } else {
                console.log("reject response");
                reject(response)
            }
        });
      }catch (err) {
        // alert('服务器出错');
        console.log("requestAjax error:",err);
      }
    },
    echoString(str) {
      if (typeof str === 'undefined' || str === null) {
          return "";
      }
      return str;
    },    
    /*******************module dialog functions**************/
    actionShown(type){
      // console.log("Dialog actionShown:",type);
    },
    actionHidden(type){
      // console.log("Dialog actionHidden:",type);
    },
    actionHideRequest(type,event){
      // console.log("Dialog actionHideRequest:",type,event);
      let dialog=this.$refs[type];
      if(dialog!==undefined && event["cv:reason"]==="close-click"){
        dialog.hide();
      }      
    }, 
    actionPrimary(type){
      // console.log("Dialog actionPrimary:",type);
      let dialog=self.$refs[type];      
    },
    actionSecondary(type){
      // console.log("Dialog actionSecondary:",type);
      let dialog=this.$refs[type];
      if(dialog!==undefined){
        dialog.hide();
      }      
    },             
  },  
  computed: {
    paramData(){
      let data={};
      data.id=this.$route.query["id"];
      return data;
    }    
  },
  mounted(){
    console.log("process.env",process.env);
  } 
};
</script>

<style lang="scss" scoped>
@import '../../styles/carbon-utils';
/deep/ .bx--modal-footer .cv-button{
  justify-content: center;
  align-items: center;
}
</style>